﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;

namespace NotAClue.Web.DynamicData
{
    /// <summary>
    /// By default, Dynamic Data doesn't blindly display all exceptions in the page,
    /// as some database exceptions may contain sensitive info.  Instead, it only displays
    /// ValidationExceptions.
    /// However, in some cases you need to display other exceptions as well.  This code
    /// shows how to achieve this.
    /// </summary>
    public class EntityFrameworkDynamicValidator : DynamicValidator
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void ValidateException(Exception exception)
        {
            // If it's not already an exception that DynamicValidator looks at
            if (!(exception is IDynamicValidatorException) && !(exception is ValidationException))
            {
                // Find the most inner exception, unwrap it.
                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }

                // Wrap it in a ValidationException so the base code doesn't ignore it
                if (ExceptionShouldBeDisplayedInPage(exception))
                {
                    exception = new ValidationException(null, exception);
                }
            }

            // Call the base on the (possibly) modified exception
            base.ValidateException(exception);
        }

        private bool ExceptionShouldBeDisplayedInPage(Exception e)
        {
            // This is where you may want to add logic that looks at the exception and
            // decides whether it should indeed be shown in the page
            return true;
        }
    }
}
